package com.k.ums.service;

import com.k.ums.config.TokenConfig;
import com.k.ums.model.Constants;
import com.k.ums.model.LoginUser;
import com.k.ums.util.CacheUtils;
import com.k.ums.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/2/21
 */
@Service
public class TokenService {

    @Autowired
    private TokenConfig tokenConfig;


    public String createToken(LoginUser loginUser) {
        String token = UUID.randomUUID().toString().replace("-", "");
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_JWT_TOKEN_KEY, token);
        loginUser.setExpireTime(System.currentTimeMillis() + tokenConfig.getExpireTime());
        loginUser.setToken(token);
        CacheUtils.set(this.getTokenKey(token), loginUser, tokenConfig.getExpireTime(), TimeUnit.SECONDS);
        return JwtUtils.createJwt(claims);
    }

    public LoginUser parseToken(HttpServletRequest request) {
        String jwtToken = request.getHeader(tokenConfig.getHeader());
        if (StringUtils.isBlank(jwtToken)) {
            return null;
        }
        Claims claims = JwtUtils.parseJwt(jwtToken);
        String token = (String) claims.get(Constants.LOGIN_JWT_TOKEN_KEY);
        LoginUser loginUser = CacheUtils.get(this.getTokenKey(token));
        return loginUser;
    }

    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        if (expireTime - System.currentTimeMillis() <= tokenConfig.getRemainingTime()) {
            this.refreshToken(loginUser);
        }
    }

    public void refreshToken(LoginUser loginUser) {
        loginUser.setExpireTime(System.currentTimeMillis() + tokenConfig.getExpireTime());
        CacheUtils.set(this.getTokenKey(loginUser.getToken()), loginUser, tokenConfig.getExpireTime(), TimeUnit.SECONDS);
    }

    private String getTokenKey(String token) {
        return Constants.LOGIN_CACHE_TOKEN_KEY + token;
    }

}
